import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import { userLoginSchema } from "~/validators/user";
export default defineEventHandler(async (event) => {
  const config = useRuntimeConfig();
  const result = await runValidate(userLoginSchema, event);
  const { account, password } = result.data;
  const user = await UserSchema.findOne({ account }).exec();

  // 报错提示不能太过精准，防止黑客攻击
  if (!user) {
    throw createError({
      statusCode: 404,
      statusMessage: "该用户不存在/密码错误",
    });
  } else {
    // 校验密码是否正确
    const verifyPwd = await bcrypt.compare(password, user.password);
    if (!verifyPwd) {
      throw createError({
        statusCode: 404,
        statusMessage: "该用户不存在/密码错误",
      });
    }

    if (user.disabled) {
      throw createError({
        statusCode: 401,
        statusMessage: "该用户已被禁用",
      });
    }
  }
  const userData = { account: user.account, _id: user._id };
  const token = jwt.sign(userData, config.jwt.secret, {
    expiresIn: config.jwt.expiresIn,
  });

  setCookie(event, "token", token, { maxAge: config.jwt.expiresIn });
  return user.toJSON();
});
